/**
 *    Copyright 2009-2020 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.learning;

import lombok.SneakyThrows;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.scripting.xmltags.OgnlCache;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.JdbcType;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import java.util.HashMap;
import java.util.Map;

/**
 * @author HanQi [Jpanda@aliyun.com]
 * @version 1.0
 * @since 2020/3/30 14:00:09
 */
public class Express {
    @Test
    @SneakyThrows
    public void ognlExpress() {
        ParameterMapping mapping = new ParameterMapping.Builder(Mockito.spy(Configuration.class), "id", Object.class)
                .javaType(String.class)
                .jdbcType(JdbcType.VARCHAR)
                .expression("_this.property=(_parameter instanceof org.apache.learning.Express)?\"id\":\"newId\"")/*添加表达式，动态处理property的值*/
                .build();

        // 构建运行环境上下文
        Map<Object, Object> values = new HashMap<>();
        // 被处理的ParameterMapping的对象
        values.put("_this", mapping);
        // Sql方法入参
        values.put("_parameter", new Object());


        // 解析表达式
        OgnlCache.getValue(mapping.getExpression(), values);

        // 成功
        Assertions.assertEquals("newId", mapping.getProperty());
    }
}
